#pragma once

class SingleClientLock
{
private:
	SingleClientLock();
public:
	~SingleClientLock();

	static SingleClientLock& Instance()
	{
		static SingleClientLock instance;
		return instance;
	}

public:
	void Lock();
	void Unlock();
	bool AlreadyExist() const;

private:
	HANDLE mHandle;
	DWORD mLastError;

	const std::wstring mMutexName;
};

inline SingleClientLock::SingleClientLock()
: mHandle(0)
, mLastError(0)
, mMutexName(L"fasttab")
{
	this->Lock();
}

inline SingleClientLock::~SingleClientLock()
{
	this->Unlock();
}

inline void SingleClientLock::Lock()
{
	mHandle = ::CreateMutex(0, FALSE, mMutexName.c_str());
	mLastError = ::GetLastError();
}

inline void SingleClientLock::Unlock()
{
	if (mHandle && mLastError == ERROR_SUCCESS)
	{
		::CloseHandle(mHandle);
		mHandle = 0;
	}
}

inline bool SingleClientLock::AlreadyExist() const
{
	return mHandle != 0 && mLastError == ERROR_ALREADY_EXISTS;
}